package edu.rakovic.elearning.pages;

import java.util.Collection;

import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;

import edu.rakovic.elearning.beans.ApplicationBean;
import edu.rakovic.elearning.beans.ExamBean;
import edu.rakovic.elearning.exceptions.RedudantAppliacationException;
import edu.rakovic.elearning.interfaces.Application;
import edu.rakovic.elearning.interfaces.Course;
import edu.rakovic.elearning.interfaces.Exam;
import edu.rakovic.elearning.interfaces.User;
import edu.rakovic.elearning.service.Applications;
import edu.rakovic.elearning.service.Courses;
import edu.rakovic.elearning.service.Exams;

public class ViewStudentApplications {
	
	@Inject
	@Property
	private Applications applications;
	
	@Inject
	@Property
	private Courses courses;
	
	@Inject
	@Property
	private Exams exams;
	
	@Property
	private Application currentApplication;
	
	@InjectPage
	private Info infoPage;
	
	// login check
	@SessionState
	private User user;

	private boolean userExists;
	
	public User getUser() {
		return user;
	}
	
	Object onActivate() {
		if (!userExists) return Login.class;
		return null;
	}
	
	void onActionFromCancel(String appId){
		Application appl = applications.retreiveSingleApplication(appId);
		//using "database applications" to perform application removal.
		appl.cancelApplication(applications);

	}
	
	Object onActionFromTake(String courseName) {
		Course course = courses.retreiveSingleCourse(courseName);
		Exam exam = new ExamBean();
			exam.executeExamCreation(user, course, exam.generateRandomMark());
			exams.save(exam);
			infoPage.setMessage(getExamResults(exam));
			return infoPage;
		
	}
	
	private String getExamResults(Exam exam){
		String passed = "";
		if(exam.isPassed()){ 
			passed = "You passed "+exam.getCourse().getName() + " with grade " + exam.getGrade();
		} else { 
			passed = "You failed "+exam.getCourse().getName() + " exam";
		}
		String examResults = ""+passed + ". Average Course grade is " + exam.getCourse().averageGrade();
		return examResults;		
	}
	
	public Collection<Application> getStudentApplications() {
		return applications.retrieveStudentApplications(getUser().getUserName());
	}

}
